from typing import Dict, List, Optional
from rich.text import Text

class MapBase:
    """地图基类"""
    def __init__(self, name: str):
        self.name = name
        self.rooms: Dict[str, Dict] = {}
        self.ascii_map: str = ""
        self.room_positions = {}  # 存储房间位置信息 {(x, y): room_name}
        self.player_init_position: str = ""  # 玩家初始位置
        
    def add_room(self, room_name: str, room_config: Dict) -> None:
        """添加房间到地图中
        
        Args:
            room_name: 房间名称
            room_config: 房间配置，包含颜色、描述、环境等信息
        """
        self.rooms[room_name] = room_config
        
    def set_room_position(self, room_name: str, x: int, y: int) -> None:
        """设置房间的坐标位置
        
        Args:
            room_name: 房间名称
            x: x坐标
            y: y坐标
        """
        self.room_positions[(x, y)] = room_name
        
    def get_room_at_position(self, x: int, y: int) -> Optional[str]:
        """获取指定坐标的房间名称
        
        Args:
            x: x坐标
            y: y坐标
            
        Returns:
            房间名称或None
        """
        return self.room_positions.get((x, y))
        
    def get_description(self, x: int, y: int) -> Optional[Text]:
        """获取指定坐标位置的描述
        
        Args:
            x: x坐标
            y: y坐标
            
        Returns:
            位置描述或None
        """
        room_name = self.get_room_at_position(x, y)
        if room_name:
            return self.get_room_description(room_name)
        return None
        
    def get_room(self, room_name: str) -> Optional[Dict]:
        """获取房间信息
        
        Args:
            room_name: 房间名称
            
        Returns:
            房间配置信息或None（如果房间不存在）
        """
        return self.rooms.get(room_name)
    
    def set_ascii_map(self, ascii_map: str) -> None:
        """设置ASCII地图
        
        Args:
            ascii_map: ASCII格式的地图字符串
        """
        self.ascii_map = ascii_map
        
    def get_ascii_map(self) -> str:
        """获取ASCII地图
        
        Returns:
            ASCII格式的地图字符串
        """
        return self.ascii_map
    
    def get_exits(self, room_name: str) -> Dict:
        """获取房间的出口信息
        
        Args:
            room_name: 房间名称
            
        Returns:
            房间的出口配置
        """
        room = self.get_room(room_name)
        return room.get("exits", {}) if room else {}
    
    def is_accessible(self, room_name: str) -> bool:
        """检查房间是否可到达
        
        Args:
            room_name: 房间名称
            
        Returns:
            房间是否可到达
        """
        room = self.get_room(room_name)
        return room.get("是否可去", False) if room else False
    
    def get_room_description(self, room_name: str) -> Text:
        """获取房间的富文本描述
        
        Args:
            room_name: 房间名称
            
        Returns:
            房间的富文本描述
        """
        room = self.get_room(room_name)
        if not room:
            return Text("房间不存在")
            
        result = Text()
        result.append(f"【{room_name}】\n", style=room.get("颜色", "white"))
        result.append(f"描述：{room.get('描述', '无描述')}\n")
        result.append(f"环境：{room.get('环境', '普通环境')}\n")
        
        if room.get("物品"):
            result.append(f"物品：{room['物品']}\n")
        if room.get("npc"):
            result.append(f"NPC：{room['npc']}\n")
            
        exits = room.get("exits", {})
        if exits:
            exit_desc = "出口："
            exit_desc += "、".join([f"{direction}({dest})" for direction, dest in exits.items()])
            result.append(exit_desc)
            
        return result 
    
    def is_valid_position(self, x: int, y: int) -> bool:
        """检查坐标位置是否有效（是否存在房间）
        
        Args:
            x: x坐标
            y: y坐标
            
        Returns:
            该位置是否有效
        """
        # 检查该位置是否有房间
        room_name = self.get_room_at_position(x, y)
        if not room_name:
            return False
            
        # 检查该房间是否可去
        room = self.get_room(room_name)
        return room.get("是否可去", False) if room else False 
    
    def set_player_init_position(self, room_name: str) -> None:
        """设置玩家在地图中的初始位置
        
        Args:
            room_name: 初始房间名称
        """
        if room_name in self.rooms:
            self.player_init_position = room_name
        else:
            raise ValueError(f"房间 {room_name} 不存在")
            
    def get_player_init_position(self) -> str:
        """获取玩家的初始位置
        
        Returns:
            初始房间名称
        """
        return self.player_init_position 